# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : process_option_view.py
# Time       ：2023/10/12 17:59
# Author     ：YangYong
# version    ：python 3.10
# Description：流程选项视图
"""
from apis.options import option_ns
from apis.orderlines.models import Process
from apis.orderlines.schema.process_schema import ProcessSchema
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel
from public.base_view import AbstractView

process_opt_marshal = MarshalModel('process_opt', option_ns)


class ProcessOptionView(AbstractView):
    url = '/process_opt'

    def __init__(self, *args, **kwargs):
        super(ProcessOptionView, self).__init__(*args, **kwargs)
        self.table_orm = Process
        self.table_schema = ProcessSchema

    @option_ns.doc(description='流程选项')
    @handle_api_error()
    def get(self):
        """流程选项"""
        objs = db.session.query(self.table_orm).filter(self.table_orm.active == 1).all()
        process_info = self.table_schema().dump(objs, many=True) or []
        response_data = list()
        if not process_info:
            return generate_response(response_data)
        for item in process_info:
            temp = dict()
            process_id = item.get('process_id')
            process_name = item.get('process_name')
            process_instance = item.get('process_instance') or []
            children = list()
            for index, instance in enumerate(process_instance):
                run_instance = {
                    'id': instance.get('process_instance_id'),
                    'name': f'第{index + 1}次运行'
                }
                children.append(run_instance)
            if children:
                temp['id'] = process_id
                temp['name'] = f'流程【{process_name}】'
                temp['children'] = children
                response_data.append(temp)
        return generate_response(response_data)
